package com.woniuxy.controller;

import com.woniuxy.annotation.MyLog;
import com.woniuxy.entity.Emp;
import com.woniuxy.service.auth.AuthService;
import com.woniuxy.service.statement.SaleService;
import com.woniuxy.service.emp.EmpService;
import com.woniuxy.util.ResultVo;
import com.woniuxy.vo.BarViewVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 马踏东京赏樱花
 */
@RestController
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private SaleService saleService;
    @Autowired
    private EmpService empService;

    @MyLog("用户登录")
    @PostMapping("auth/login")
    public ResultVo login(@RequestBody Emp emp, HttpServletRequest request) {
        System.out.println(emp);
        Emp loginEmp = authService.login(emp.getEmpUacc(), emp.getEmpUpwd());
        request.getSession().setAttribute("loginEmp", loginEmp);
        return ResultVo.success(loginEmp);
    }

    @MyLog("修改密码")
    @PostMapping("auth/changePassword")
    public ResultVo changePassword(@RequestBody Map<String, String> map, HttpServletRequest request) {
        Emp emp = (Emp) request.getSession().getAttribute("loginEmp");
        // 旧密码
        String pass = map.get("pass");
        // 新密码
        String checkPass = map.get("checkPass");
        Emp dbEmp = empService.findOne(emp.getEmpId());
        // 根据 emp id 进行比较
        if (pass.equals(dbEmp.getEmpUpwd())) {
            emp.setEmpUpwd(checkPass);
            int rows = empService.update(emp);
            return ResultVo.success("密码更新成功!");
        } else {
            return ResultVo.failure("原始密码输入错误!!!");
        }
    }


    @MyLog("修改密码")
    @PostMapping("auth/updateUpwd")
    public ResultVo updateUpwd(HttpServletRequest request) {
        String oldUpwd = request.getParameter("oldUpwd");
        String newUpwd = request.getParameter("newUpwd");
        Emp emp = (Emp) request.getSession().getAttribute("upwd");

        authService.updateUpwd(oldUpwd, newUpwd, emp.getEmpId());

        return ResultVo.success(emp.getEmpUpwd());
    }

    //    @MyLog("用户退出登录")
    @PostMapping("auth/logout")
    public ResultVo logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return ResultVo.success("退出成功");
    }

    @PostMapping("/barVo")
    public ResultVo barVo() {
        List<BarViewVo> barVo = saleService.barVoList();
        return barVo != null ? ResultVo.success("ok", barVo) : ResultVo.failure("no");
    }
}
